var fs = require('fs');
var mysql = require('mysql');
var superagent = require('superagent');
var cheerio = require('cheerio');

require('superagent-proxy')(superagent);

var mysqlCloudMusic = require('./config').mysqlCloudMusic;
var mysqlProxy = require('./config').mysqlProxy;

function main() {
    var ipList = [];
    var ipIndex = 0;
    var proxy = '';

    function changeIp() {
        if (ipIndex < ipList.length - 1) {
            ipIndex += 1;
        } else {
            ipIndex = 0;
        }
        setProxy();
    }

    function setProxy() {
        var item = ipList[ipIndex];
        console.log(item);

        var ip = item.ip;
        var port = item.port;

        proxy = `http://${ip}:${port}`;
        console.log('proxy');

        console.log(proxy);

    }

    var connection1 = mysql.createConnection(mysqlProxy);
    var query1 = 'select * from ip_table1 where success_count>=6';
    connection1.connect();
    connection1.query(query1, function (err, res) {
        if (err) {
            console.log('query1 error');
            console.log(err);

        } else {
            ipList = res;
            console.log(ipList.length);
            setProxy();
            console.log(proxy);

            // setInterval(() => {
            //     changeIp();
            // }, 300 * 1000);
            for (var i = 0; i < 5; i++) {
                var offset = 10 * i;
                getArtist({ offset: offset });
            }
        }
    });
    connection1.end();

    function getArtist(options) {
        console.log(options);

        let offset = 0;
        if (options && options.offset) {
            offset = options.offset;
        }
        var connection = mysql.createConnection(mysqlCloudMusic);
        var queryString = 'select * from artist order by album_version limit 1 offset ' + offset;

        connection.query(queryString, function (err, res) {
            if (err) {
                console.log('query2 err');
                console.log(err);

            } else {
                if (res.length === 0) {
                    console.log('no artist');
                    setTimeout(() => {
                        getArtist(options);
                    }, 3600 * 1000);
                } else {
                    var artist = res[0];
                    // console.log(artist);

                    options.artist = artist;
                    getAlbum(options);
                }
            }
        });
        connection.end();
    }

    function getAlbum(options) {
        // console.log(options);

        const artist = options.artist;
        const artistId = artist.id;
        let url = `https://music.163.com/artist/album?id=${artistId}`;
        if (options.url) {
            url = options.url;
        }
        superagent.get(url)
            .timeout(3000)
            .proxy(proxy)
            .end(function (err, res) {
                console.log(url);

                if (err) {
                    console.log('http error');
                    console.log(url);

                    console.log(proxy);
                    console.log();
                    // process.exit();
                    changeIp();
                    getArtist({
                        offset: options.offset
                    });

                } else {
                    console.log('http success');

                    var text = res.text;
                    fs.writeFile('html/album.html', text, function () { })

                    var $ = cheerio.load(text);
                    var m_song_module = $('#m-song-module');

                    var list2 = m_song_module.find('li');
                    console.log(list2.length);

                    // var albumName=list2.find('p').text();
                    // console.log(albumName);
                    const albumList = [];
                    list2.each((i, element) => {
                        var item = list2.eq(i);
                        var name = item.find('p').eq(0).text().replace(/\n/g, '');
                        console.log(name);
                        var id = item.find('p>a').eq(0).attr().href.replace(/\/album\?id=/g, '');
                        console.log(id);
                        var time = item.find('p').eq(1).text();

                        var value = [id, name, artistId, time];
                        console.log(value);
                        albumList.push(value);
                    });
                    console.log(albumList);


                    var u_page = $('.u-page');
                    if (u_page.length > 0) {
                        console.log('u-page >0');
                        var znxt = $('.znxt').eq(0);
                        var href = znxt.attr().href;
                        var url2;
                        if (href.match(/javascript.?/g)) {
                            // fn3();
                            var albumListLength = albumList.length;
                            if (albumListLength > 0) {
                                options.albumList = albumList;
                                upload(options);
                            } else {
                                feedback(options);
                            }
                        } else {
                            options.url = 'https://music.163.com' + znxt.attr().href;
                            console.log('url');
                            console.log(url);
                            getAlbum(options);
                        }
                    } else {
                        var albumListLength = albumList.length;
                        if (albumListLength > 0) {
                            options.albumList = albumList;
                            upload(options);
                        } else {
                            feedback(options);
                        }
                    }




                }
            })

    }


    function upload(options) {
        const albumList = options.albumList;

        var connection = mysql.createConnection(mysqlCloudMusic);
        var queryString = 'insert ignore into album(id, name, artist_id, time) values ?';
        connection.connect();
        connection.query(queryString, [albumList], function (err, res) {
            if (err) {
                console.log('query3 err');
                console.log(err);
                console.log('albumList');

                console.log(albumList);

                getArtist({
                    offset: options.offset
                });
            } else {
                console.log(res);
                // artistListUpdated.push(artistId);

                feedback(options);
            }
        });
        connection.end();
    }
    function feedback(options) {
        const artist = options.artist;
        const artistId = artist.id;

        var connection4 = mysql.createConnection(mysqlCloudMusic);

        var album_version = 1;
        if (artist.album_version) {
            album_version = artist.album_version + 1;
        }
        var query4 = `UPDATE artist   
         SET album_version=${album_version} where id =${artistId};`
        console.log(query4);
        connection4.query(query4, function (err, res) {
            if (err) {
                console.log('query4 err');

            } else {
                console.log('query4 res');
                setTimeout(() => {
                    getArtist({
                        offset: options.offset
                    })
                }, 200);
            }
        });
        connection4.end();

    }
}

for (let i = 0; i < 10; i++) {
    const offset = 10 * i;
    console.log(offset);

    main()
}